<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j page-cart">
    <div class="content">
      <div class="step-box">
        <div class="left">
          <span class="img" />
          <span class="text">{{ $t('cart.cart') }}</span>
        </div>
        <div class="steps">
          <div class="item active">
            <div class="number">
              step 01.
            </div>
            <div class="text">
              {{ $t('cart.selectProductToBuy') }}
            </div>
          </div>
          <div class="item">
            <div class="number">
              step 02.
            </div>
            <div class="text">
              {{ $t('cart.confirmOrderInformation') }}
            </div>
          </div>
          <div class="item">
            <div class="number">
              step 03.
            </div>
            <div class="text">
              {{ $t('cart.payToCompleteTheOrder') }}
            </div>
          </div>
        </div>
      </div>
      <div class="cart-tab">
        <div
          class="tab-check"
        >
          <template v-if="shopCarts.length">
            <div
              class="checkbox default"
              :class="{ checked: allChecked, default: !allChecked }"
              @click="onCheckAll"
            />
            <span class="text">{{ $t('all') }}</span>
          </template>
        </div>
        <div class="tab-img">
&nbsp;
        </div>
        <div class="tab-name">
          {{ $t('products') }}
        </div>
        <div class="tab-price">
          {{ $t('priceOne') }}
        </div>
        <div class="tab-number">
          {{ $t('quantity') }}
        </div>
        <div class="tab-total">
          {{ $t('subtotal') }}
        </div>
        <div class="tab-action">
          {{ $t('operation') }}
        </div>
      </div>
      <empty
        v-if="isEmpty && !expiryProdList?.length"
        :text="$t('cart.yourShoppingCartIsEmpty')"
        :back="$t('cart.goShopping')"
        :src-type="4"
      />
      <div
        v-for="(shopCart, shopIndex) in shopCarts"
        :key="shopIndex"
      >
        <div class="cart-con">
          <div class="shop-box">
            <div class="shop-msg">
              <div
                class="checkbox default"
                :class="{ checked: shopCart.checked && isCannotDelivery(shopCart.shopCartItemDiscounts), default: !shopCart.checked }"
                @click="onCheckShop(shopIndex)"
              />
              <span
                v-if="shopCart.shopId === 1"
                class="self"
              >{{ $t('prodDetail.selfEmployed') }}</span>
              <router-link
                :to="{
                  path: 'shop-index',
                  query: {
                    sid: shopCart.shopId
                  }
                }"
                class="shop-name"
              >
                {{
                  shopCart.shopName
                }}
              </router-link>
            </div>
          </div>
          <div class="activity-list">
            <div
              v-for="(shopCartItem,
                      shopCartItemIndex) in shopCart.shopCartItemDiscounts"
              :key="shopCartItemIndex"
              class="cart-con"
            >
              <div class="activity-list">
                <div
                  v-if="shopCartItem.chooseDiscountItemDto"
                  class="activity-msg"
                >
                  <div class="a-info">
                    <div class="icon">
                      {{
                        [$t('cart.fullReduction'), $t('cart.fullPieceDiscount'), $t('cart.fullDiscount'), $t('cart.discountOnFullPieces')][
                          shopCartItem.chooseDiscountItemDto.discountRule
                        ]
                      }}
                    </div>
                    <div
                      v-if="
                        shopCartItem.chooseDiscountItemDto.discountRule == 0
                      "
                      class="text"
                    >
                      <span
                        v-if="shopCartItem.chooseDiscountItemDto.reduceAmount"
                      >
                        {{ $t('cart.activeItemsAreFullyPurchased') }}￥{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[0]
                        }}.{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[1]
                        }}（
                        <span class="text-red">{{ $t('cart.reduced') }}￥{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.reduceAmount
                          )[0]
                        }}.{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.reduceAmount
                          )[1]
                        }}</span>）
                      </span>
                      <span v-else>{{ $t('cart.activeItemsPurchasedOver') }}￥{{
                        parsePrice(
                          shopCartItem.chooseDiscountItemDto.needAmount
                        )[0]
                      }}.{{
                        parsePrice(
                          shopCartItem.chooseDiscountItemDto.needAmount
                        )[1]
                      }}
                        {{ $t('cart.getAFullDiscount') }}</span>
                    </div>
                    <div
                      v-if="
                        shopCartItem.chooseDiscountItemDto.discountRule == 1
                      "
                      class="text"
                    >
                      <span
                        v-if="shopCartItem.chooseDiscountItemDto.reduceAmount"
                      >
                        {{ $t('cart.activeItemsAreFullyPurchased') }}
                        {{ shopCartItem.chooseDiscountItemDto.needAmount }}件{{ $t('items') }}（
                        <span class="text-red">{{ $t('cart.reduced') }}￥{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.reduceAmount
                          )[0]
                        }}.{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.reduceAmount
                          )[1]
                        }}</span>）
                      </span>
                      <span v-else>{{ $t('cart.activeItemsPurchasedOver') }}
                        {{ shopCartItem.chooseDiscountItemDto.needAmount }}
                        {{ $t('items') }}{{ $t('cart.getAFullDiscount') }}
                      </span>
                    </div>
                    <div
                      v-if="
                        shopCartItem.chooseDiscountItemDto.discountRule == 2
                      "
                      class="text"
                    >
                      <span
                        v-if="shopCartItem.chooseDiscountItemDto.reduceAmount"
                      >
                        {{ $t('cart.activeItemsAreFullyPurchased') }}￥{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[0]
                        }}.{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.needAmount
                          )[1]
                        }}（
                        <span class="text-red">{{ $t('cart.reduced') }}￥{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.reduceAmount
                          )[0]
                        }}.{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.reduceAmount
                          )[1]
                        }}</span>）
                      </span>
                      <span v-else>{{ $t('cart.activeItemsPurchasedOver') }}￥{{
                        parsePrice(
                          shopCartItem.chooseDiscountItemDto.needAmount
                        )[0]
                      }}.{{
                        parsePrice(
                          shopCartItem.chooseDiscountItemDto.needAmount
                        )[1]
                      }}
                        {{ $t('cart.enjoyAFullDiscount') }}</span>
                    </div>
                    <div
                      v-if="
                        shopCartItem.chooseDiscountItemDto.discountRule == 3
                      "
                      class="text"
                    >
                      <span
                        v-if="shopCartItem.chooseDiscountItemDto.reduceAmount"
                      >
                        {{ $t('cart.activeItemsAreFullyPurchased') }}
                        {{ shopCartItem.chooseDiscountItemDto.needAmount }}{{ $t('items') }}（
                        <span class="text-red">{{ $t('cart.reduced') }}￥{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.reduceAmount
                          )[0]
                        }}.{{
                          parsePrice(
                            shopCartItem.chooseDiscountItemDto.reduceAmount
                          )[1]
                        }}</span>）
                      </span>
                      <span v-else>{{ $t('cart.activeItemsPurchasedOver') }}
                        {{ shopCartItem.chooseDiscountItemDto.needAmount }}
                        {{ $t('items') }} {{ $t('cart.enjoyAFullDiscount') }}</span>
                    </div>
                    <router-link
                      :to="
                        '/discount-detail?discountId=' +
                          shopCartItem.chooseDiscountItemDto.discountId
                      "
                      class="link"
                    >
                      {{
                        shopCartItem.chooseDiscountItemDto.reduceAmount
                          ? $t('cart.goToAdd')
                          : $t('cart.goToTheList')
                      }}
                      <span class="arr">>></span>
                    </router-link>
                  </div>
                  <div class="a-price">
                    <div class="discount">
                      <span
                        v-if="shopCartItem.chooseDiscountItemDto.reduceAmount"
                      >-￥{{
                        parsePrice(
                          shopCartItem.chooseDiscountItemDto.reduceAmount
                        )[0]
                      }}.{{
                        parsePrice(
                          shopCartItem.chooseDiscountItemDto.reduceAmount
                        )[1]
                      }}</span>
                    </div>
                  </div>
                </div>
                <!-- 套餐提示 -->
                <div
                  v-if="shopCartItem.chooseComboItemDto"
                  class="combo-msg"
                >
                  <div class="combo-info">
                    <span class="combo-icon">{{ $t('cart.combo') }}</span>
                    <span class="combo-name">{{ shopCartItem.chooseComboItemDto.name }}</span>
                    <template v-if="shopCartItem.chooseComboItemDto.preferentialAmount">
                      (<span class="combo-reduce"> {{ $t('cart.reduced') }} {{ shopCartItem.chooseComboItemDto.preferentialAmount }} {{ $t('memberCenter.yuan') }}</span>)
                    </template>
                  </div>
                  <div class="combo-unit-price">
                    ￥{{ parsePrice(shopCartItem.chooseComboItemDto.comboAmount)[0] }}.{{ parsePrice(shopCartItem.chooseComboItemDto.comboAmount)[1] }}
                  </div>
                  <div class="combo-count">
                    <!-- @click="updateBasket(shopCartItem.shopCartItems[0], -1)" -->
                    <span
                      class="reduce"
                      :class="{ limit: shopCartItem.chooseComboItemDto.comboCount === 1 }"
                      @click="onChangeNumber(shopIndex, shopCartItemIndex, 0, -1)"
                    >-</span>
                    <input
                      v-model="shopCartItem.chooseComboItemDto.comboCount"
                      type="number"
                      class="number"
                      maxlength="4"
                      oninput="if(value>9999)value=9999"
                      @focus="handleInputFocus(shopCartItem.chooseComboItemDto.comboCount)"
                      @blur="comboHandleInputBlur($event, shopIndex, shopCartItemIndex)"
                    >
                    <!-- @click="updateBasket(shopCartItem.shopCartItems[0], 1)" -->
                    <span
                      class="increase"
                      :class="{ limit: shopCartItem.chooseComboItemDto.comboCount === 9999 }"
                      @click="onChangeNumber(shopIndex, shopCartItemIndex, 0, 1)"
                    >+</span>
                  </div>
                  <div class="combo-total-price">
                    ￥{{ parsePrice(shopCartItem.chooseComboItemDto.comboAmount * shopCartItem.chooseComboItemDto.comboCount)[0] }}.{{ parsePrice(shopCartItem.chooseComboItemDto.comboAmount * shopCartItem.chooseComboItemDto.comboCount)[1] }}
                  </div>
                  <div
                    class="combo-del-btn"
                    @click="openPopup(shopCartItem.shopCartItems[0].basketId)"
                  >
                    {{ $t('delete') }}
                  </div>
                </div>

                <div
                  v-for="(prod, prodIndex) in shopCartItem.shopCartItems"
                  :key="prodIndex"
                  class="activity-goods"
                >
                  <!-- 商品项 -->
                  <div
                    :class="[
                      prod.checked ? 'active item' : 'item',
                      (prod.discountId > 0 && shopCartItem.chooseDiscountItemDto) || shopCartItem.comboId ? 'activity-goods-checked' : '',
                    ]"
                  >
                    <div class="item-goods">
                      <div class="tab-check">
                        <div
                          v-if="!prod.comboId || (prod.comboId && !prod.parentBasketId)"
                          class="checkbox"
                          checkbox
                          :class="{
                            checked: prod.isDelivery && prod.checked,
                            default: prod.isDelivery && !prod.checked,
                            disabled: !prod.isDelivery
                          }"
                          @click="onCheckProdItem(shopIndex, shopCartItemIndex, prodIndex)"
                        />
                      </div>
                      <div class="tab-img">
                        <router-link
                          :to="{
                            path:'/detail',
                            query:{
                              prodId:prod.prodId
                            }
                          }"
                          target="_blank"
                          class="img-box"
                        >
                          <img-show
                            v-if="prod.pic"
                            :src="checkFileUrl(prod.pic)"
                            alt
                          />
                          <img
                            v-else
                            src="@/assets/img/def.png"
                            alt
                          >
                          <span
                            v-if="!prod.isDelivery || (shopCartItem.chooseComboItemDto && !shopCartItem.chooseComboItemDto.isDelivery)"
                            class="undelivered-tag"
                          >{{ $t('cart.undelivered') }}
                          </span>
                        </router-link>
                      </div>
                      <div class="tab-name">
                        <router-link
                          :to="{
                            path:'/detail',
                            query:{
                              prodId:prod.prodId
                            }
                          }"
                          target="_blank"
                          class="name"
                        >
                          {{
                            prod.prodName
                          }}
                        </router-link>
                        <span
                          class="sku"
                          @click="getSkuListByProdId(prod)"
                        >
                          <SelectSku
                            v-if="prod.skuName && prod.skuName.trim()"
                            :sku-id="prod.skuId"
                            :sku-name="prod.skuName"
                            :prod-id="prod.prodId"
                            :combo-id="prod.comboId"
                            @get-sku="onSetSku"
                          />
                        </span>
                      </div>
                      <div class="tab-price">
                        <div class="unit-price">
                          ￥{{ parsePrice(shopCartItem.chooseComboItemDto ? prod.comboPrice : prod.price)[0] }}.{{
                            parsePrice(shopCartItem.chooseComboItemDto ? prod.comboPrice : prod.price)[1]
                          }}
                        </div>
                        <div class="promotion-box">
                          <div
                            v-if="prod.discountId > 0 || prod.discountId == -1"
                            class="p-tit"
                            :data-basketid="prod.basketId"
                            @click.prevent="onShowDisList(prod.basketId, prod.discountId)"
                          >
                            {{ $t('promotion') }}
                          </div>
                          <transition name="fade">
                            <div
                              v-if="
                                showDiscountsList &&
                                  prod.basketId == currentBasketId
                              "
                              class="p-con"
                            >
                              <div class="p-items-con">
                                <div
                                  v-for="(discountItem, index) in prod.discounts"
                                  :key="discountItem.discountId"
                                  class="p-item"
                                >
                                  <input
                                    :id="index"
                                    type="radio"
                                    class="radio"
                                    :name="prod.prodId"
                                    :checked="
                                      discountItem.discountId == prod.discountId
                                    "
                                    @change="radioChange(discountItem.discountId)"
                                  >
                                  <label
                                    :for="index"
                                    class="p-info"
                                  >{{
                                    discountItem.discountName
                                  }}</label>
                                </div>
                                <div class="p-item">
                                  <input
                                    id="nodiscount"
                                    type="radio"
                                    class="radio"
                                    :name="prod.prodId"
                                    :checked="prod.discountId == -1"
                                    @change="radioChange(-1)"
                                  >
                                  <label
                                    for="nodiscount"
                                    class="p-info"
                                  >{{ $t('cart.noEventDiscount') }}</label>
                                </div>
                              </div>
                              <div class="p-btns">
                                <a
                                  href="javascript:void(0)"
                                  class="sure"
                                  @click="onChooseDiscount(prod)"
                                >{{ $t('determine') }}</a>
                                <a
                                  href="javascript:void(0)"
                                  class="cancel"
                                  @click="showDiscountsList = false"
                                >{{ $t('cancel') }}</a>
                              </div>
                            </div>
                          </transition>
                        </div>
                      </div>
                      <div class="tab-number">
                        <div class="goods-number">
                          <span
                            v-if="!prod.comboId"
                            class="reduce"
                            :class="{ limit: prod.prodCount === 1 }"
                            @click="onChangeNumber(shopIndex, shopCartItemIndex, prodIndex, -1)"
                          >-</span>
                          <input
                            v-model="prod.prodCount"
                            type="number"
                            class="number"
                            :readonly="prod.comboId?true:false"
                            maxlength="4"
                            oninput="if(value>9999)value=9999"
                            @focus="handleInputFocus(prod.prodCount)"
                            @blur="handleInputBlur($event, shopIndex, shopCartItemIndex, prodIndex)"
                          >
                          <span
                            v-if="!prod.comboId"
                            :class="{ limit: prod.prodCount === 9999 }"
                            class="increase"
                            @click="onChangeNumber(shopIndex, shopCartItemIndex, prodIndex, 1)"
                          >+</span>
                        </div>
                      </div>
                      <div class="tab-total">
                        ￥{{ parsePrice(prod.prodCount * (prod.comboId ? prod.comboPrice : prod.price))[0] }}.{{
                          parsePrice(prod.prodCount * (prod.comboId ? prod.comboPrice : prod.price))[1]
                        }}
                      </div>
                      <div class="tab-action">
                        <a
                          v-if="prod.prodType !== 5"
                          href="JavaScript:;"
                          class="action-a collect"
                          :style="$t('language')=='en'?moveToFavorites:''"
                          @click="collection(shopIndex, shopCartItemIndex, prodIndex)"
                        >{{ $t('cart.moveToFavorites') }}</a>
                        <a
                          v-if="!prod.comboId"
                          href="JavaScript:;"
                          class="action-a del"
                          @click="openPopup(prod.basketId)"
                        >{{ $t('delete') }}</a>
                      </div>
                    </div>
                    <!-- 赠品展示 -->
                    <div
                      v-if="prod.giveaway"
                      class="gift-con"
                    >
                      <div
                        v-for="(giveawayItem, giveawayIndex) in prod.giveaway.giveawayProds"
                        :key="giveawayIndex"
                        class="gift-item"
                      >
                        <router-link
                          class="gift-item-name"
                          :to="{
                            path:'/detail',
                            query:{
                              prodId:giveawayItem.prodId
                            }
                          }"
                          target="_blank"
                        >
                          {{ $t('cart.giveaways') }} {{ giveawayItem.prodName }}
                          <span class="gift-item-sku-name">{{ giveawayItem.skuName }} x{{ giveawayItem.giveawayNum }}</span>
                        </router-link>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 失效商品 -->
      <div
        v-if="expiryProdList.length"
        class="cart-con"
      >
        <div class="shop-box invalid">
          <div class="shop-msg">
            <!-- <span class="self">自营</span> -->
            <span class="shop-name">{{ $t('collection.failedProducts') }}</span>
          </div>
        </div>
        <div
          v-for="(prodItem, prodIndex) in expiryProdList"
          :key="prodIndex"
          class="item invalid"
        >
          <div class="item-box">
            <div class="tab-check">
              <div class="invalid-text">
                {{ $t("cart.failed") }}
              </div>
            </div>
            <div class="tab-img">
              <span class="img-box">
                <ImgShow :src="prodItem.pic" />
              </span>
            </div>
            <div class="tab-name">
              <span class="name">{{ prodItem.prodName }}</span>
              <span class="sku">{{ prodItem.skuName }}</span>
            </div>
            <div class="tab-price">
              ￥{{ parsePrice(prodItem.skuPriceFee)[0] }}.{{ parsePrice(prodItem.skuPriceFee)[1] }}
            </div>
            <div class="tab-number">
              <div class="goods-number">
                {{ prodItem.prodCount }}
              </div>
            </div>
            <div class="tab-total">
              ￥{{ parsePrice(prodItem.totalAmount)[0] }}.{{ parsePrice(prodItem.totalAmount)[1] }}
            </div>
            <div class="tab-action">
              <!-- <a href="" class="action-a collect">相似产品</a> -->
              <span
                class="action-a del"
                @click="openPopup(prodItem.basketId)"
              >{{ $t("delete") }}</span>
            </div>
          </div>
        </div>
      </div>

      <div
        v-if="shopCarts.length"
        class="cart-bottom"
      >
        <div class="total-box">
          <div class="check-all">
            <div
              class="checkbox"
              :class="{ checked: allChecked, default: !allChecked }"
              @click="onCheckAll"
            />
            <span
              class="text"
              @click="onCheckAll"
            >{{ $t('cart.selectAll') }}</span>
          </div>
          <a
            href="JavaScript:;"
            class="del-selected"
            @click="openPopup()"
          >{{ $t('cart.deleteSelectedProducts') }}</a>
        </div>
        <div class="settlement-box">
          <div class="price-box">
            <div class="total-price amount">
              {{ $t('cart.selected') }}
              <span class="number">{{ count }}</span>{{ $t('cart.itemsProducts') }}&nbsp;&nbsp;&nbsp;
              {{ $t('cart.totalPrice') }}：
              <span class="text">¥{{ parsePrice(finalMoney)[0] }}.{{
                parsePrice(finalMoney)[1]
              }}</span>
            </div>
            <div class="discount-price">
              <span
                v-if="freightAmount"
                class="text"
              >
                {{ $t('submitOrder.shippingFee') }}：
                ¥{{ parsePrice(freightAmount)[0] }}.{{
                  parsePrice(freightAmount)[1]
                }}</span>
              <span class="text">
                {{ $t('cart.offers') }}：
                -¥{{ parsePrice(totalReduceMoney)[0] }}.{{
                  parsePrice(totalReduceMoney)[1]
                }}</span>
            </div>
          </div>
          <a
            href="JavaScript:;"
            class="btn"
            :style="{fontSize:$t('language')=='en'?'14px':'16px'}"
            @click="onSubmit()"
          >{{ $t('cart.goToSettlement') }}</a>
        </div>
      </div>
      <div
        v-if="isPopup"
        class="popup-mask"
      />
      <!-- 删除提示弹窗 -->
      <div
        v-if="isPopup"
        class="popup-box"
      >
        <div class="tit">
          <div class="text">
            {{ $t('tips') }}
          </div>
          <div
            class="close"
            @click="closePopup()"
          />
        </div>
        <div class="con">
          <div class="tip">
            <div class="tip-icon warning" />
            <div class="tip-info">
              <div class="result">
                {{ $t('cart.deleteThisItem') }}
              </div>
              <div class="date">
                {{ $t('cart.removeCart') }}
              </div>
              <div class="btns">
                <a
                  href="JavaScript:;"
                  class="btn-r"
                  @click="onDeleteProd"
                >{{ $t('delete') }}</a>
                <a
                  href="JavaScript:;"
                  class="btn-g"
                  @click="closePopup"
                >{{ $t('cancel') }}</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as util from '@/utils'
import { tapLog } from '@/utils/flow.js'
import SelectSku from '@/components/select-sku/index.vue'
import Empty from '@/components/empty-all-tips/index.vue'
import { ElMessage } from 'element-plus'

const shopCarts = ref([])
const allChecked = ref(true)
const count = ref(0)
const finalMoney = ref(0)
const freightAmount = ref(0)
const totalReduceMoney = ref(0)
const isPopup = ref(false)
const showDiscountsList = ref(false) // 促销活动显隐
const currentBasketId = ref('')
const moveToFavorites = reactive({
  position: 'relative',
  left: '-25px'
})
let switchDiscountId = ''
// 当前修改的购物车商品项
let currentProdItem = {}

let basketReqData = [] // 请求购物车的数据
let delBasketIds = []
let totalChangeNum = 0
let timer = null
const isEmpty = ref(false)
onMounted(() => {
  // 设置网页标题
  document.title = $t('cart.cart')
  loadBasketData()
  getExpiryProdList() // 获取过期的商品列表
})

let curProdNum = 0

/**
 * 输入框聚焦
 */
const handleInputFocus = (num) => {
  curProdNum = num
}

/**
 * 直接修改购物车数量
 */
const instance = getCurrentInstance()

const handleInputBlur = ($event, shopIndex, shopCartItemIndex, prodIndex) => {
  totalChangeNum = 0
  if ($event.target.value < 0) {
    $event.target.value = -$event.target.value
    shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].shopCartItems[prodIndex].prodCount = $event.target.value
    instance.proxy.$forceUpdate()
  }
  if (!$event.target.value || $event.target.value == 0) {
    shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].shopCartItems[prodIndex].prodCount = 1
    $event.target.value = 1
    instance.proxy.$forceUpdate()
  }
  const changeNumber = $event.target.value - curProdNum
  if (changeNumber === 0) {
    return
  }
  if (changeNumber % 1 !== 0 || !$event.target.value) {
    shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].shopCartItems[prodIndex].prodCount = curProdNum
    instance.proxy.$forceUpdate()
    ElMessage.warning('请输入正确的数量')
    return
  }
  onChangeNumber(shopIndex, shopCartItemIndex, prodIndex, changeNumber, true)
}

// 套餐修改数量
const comboHandleInputBlur = ($event, shopIndex, shopCartItemIndex) => {
  totalChangeNum = 0
  if ($event.target.value < 0) {
    $event.target.value = -$event.target.value
    shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].chooseComboItemDto.comboCount = $event.target.value
    instance.proxy.$forceUpdate()
  }
  if (!$event.target.value || $event.target.value == 0) {
    shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].chooseComboItemDto.comboCount = 1
    $event.target.value = 1
  }
  const changeNumber = $event.target.value - curProdNum
  if (changeNumber === 0) {
    return
  }
  if (changeNumber % 1 !== 0 || !$event.target.value) {
    shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].chooseComboItemDto.comboCount = curProdNum
    instance.proxy.$forceUpdate()
    ElMessage.warning('请输入正确的数量')
    return
  }
  onChangeNumber(shopIndex, shopCartItemIndex, 0, changeNumber, true)
}

/**
 * 加载购物车
 */
const loadBasketData = () => {
  isEmpty.value = false
  http.post('/p/shopCart/info').then(({ data }) => {
    const isShopCarts = data.shopCarts
    const unDeliveryBasketIds = [] // 不可配送商品的购物车id集合
    isShopCarts.forEach(shopCart => {
      shopCart.shopCartItemDiscounts.forEach(shopCartItemDiscount => {
        let comboItemDto = null
        if (shopCartItemDiscount.chooseComboItemDto !== null) {
          comboItemDto = shopCartItemDiscount.chooseComboItemDto
          // 套餐商品是否全部为可配送商品
          comboItemDto.isDelivery = shopCartItemDiscount.shopCartItems.every(it => it.isDelivery)
        }
        shopCartItemDiscount.shopCartItems.forEach(shopCartItem => {
          shopCartItem.checked = shopCartItem.isChecked
          // 不可配送商品的购物车id集合
          if (shopCartItem.checked && (!shopCartItem.isDelivery || (comboItemDto && !comboItemDto.isDelivery))) {
            unDeliveryBasketIds.push({ basketId: shopCartItem.basketId, isChecked: 0 })
          }
        })
      })
    })
    if (unDeliveryBasketIds.length > 0) {
      basketReqData = unDeliveryBasketIds
      onShopCartSelect()
    }
    shopCarts.value = isShopCarts
    isEmpty.value = !shopCarts.value.length
    finalMoney.value = data.finalMoney
    freightAmount.value = data.freightAmount
    totalReduceMoney.value = data.totalReduceMoney
    count.value = data.count
    // 检查全选状态
    checkAllSelected()
    // 重新计算购物车总数量
    getCartCount()
    // 清空请求数据
    basketReqData = []
  })
}

/**
 * 去结算
 */
const router = useRouter()
const onSubmit = () => {
  const isShopCarts = shopCarts.value
  const basketIds = []
  isShopCarts.forEach(shopCart => {
    const shopCartItemDiscounts = shopCart.shopCartItemDiscounts
    shopCartItemDiscounts.forEach(shopCartItemDiscount => {
      shopCartItemDiscount.shopCartItems.forEach(shopCartItem => {
        if (shopCartItem.checked) {
          // 已选择的购物车id
          basketIds.push(shopCartItem.basketId)
        }
      })
    })
  })
  if (basketIds.length < 1 || basketIds.length > 50) {
    ElMessage({
      message: $t(basketIds.length < 1 ? 'cart.pleaseSelectAtLeastOneItem' : 'cart.basketCountOver'),
      type: 'error',
      duration: 1000
    })
    return
  }
  sessionStorage.setItem('bbcBasketIds', JSON.stringify(basketIds))
  router.push({ path: '/submit-order', query: { orderEntry: 0 } })
}

// 收藏商品
const collection = util._debounce((shopIndex, shopCartItemIndex, prodIndex) => {
  const item = shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].shopCartItems[prodIndex]
  const prodId = item.prodId
  http.get('/p/user/collection/isCollection', { params: { prodId } }).then(({ data }) => {
    if (data == true) {
      ElMessage({
        message: $t('cart.theProductIsAlreadyInTheFavorites'),
        type: 'success',
        duration: 1000
      })
    } else {
      http.post('/p/user/collection/orderProdCollectionAll', item.prodId).then(() => {
        ElMessage({
          message: $t('prodDetail.collectionSuccess'),
          type: 'success',
          duration: 1000
        })
      })
    }
  })
}, 500)

// 打开弹窗
const openPopup = (basketId) => {
  delBasketIds = basketId ? [basketId] : []
  checkDeleteProdNum()
}
// 关闭弹窗
const closePopup = () => {
  isPopup.value = false
  delBasketIds = []
}

/**
 * 每一项的选择事件
 */
const onCheckProdItem = (shopIndex, shopCartItemIndex, prodIndex) => {
  const isShopCarts = shopCarts.value
  const shopCartItemDiscounts = isShopCarts[shopIndex].shopCartItemDiscounts // 获取购物车列表
  const prod = shopCartItemDiscounts[shopCartItemIndex].shopCartItems[prodIndex]
  if (!prod.isDelivery) return // 不可配送商品不可勾选
  const checked = prod.checked // 获取当前商品的选中状态
  // 如果勾选的是套餐商品，需要变更该套餐下搭配商品的勾选状态
  if (prod.comboId) {
    shopCartItemDiscounts[shopCartItemIndex].shopCartItems.forEach(el => {
      basketReqData.push({
        basketId: el.basketId,
        isChecked: !checked ? 1 : 0
      })
    })
  } else {
    basketReqData.push({
      basketId: prod.basketId,
      isChecked: !prod.isChecked ? 1 : 0
    })
  }
  onShopCartSelect()
}

const isCannotDelivery = computed(() => {
  return (shopList) => {
    let arrData = 0
    shopList.forEach(shopCartItem => {
      const cItems = shopCartItem.shopCartItems
      const comboItemDto = shopCartItem.chooseComboItemDto
      for (let j = 0; j < cItems.length; j++) {
        // 过滤掉不可配送的商品
        if (!cItems[j].isDelivery || (comboItemDto && !comboItemDto.isDelivery)) continue
        arrData++
      }
    })
    return arrData > 0
  }
})

/**
 * 店铺 勾选/取选 事件
 */
const onCheckShop = (shopIndex) => {
  const isShopCarts = shopCarts.value
  const checked = isShopCarts[shopIndex].checked // 获取当前店铺的选中状态
  isShopCarts[shopIndex].checked = !checked // 改变状态
  isShopCarts[shopIndex].shopCartItemDiscounts.forEach(shopCartItem => {
    const cItems = shopCartItem.shopCartItems
    const comboItemDto = shopCartItem.chooseComboItemDto
    for (let j = 0; j < cItems.length; j++) {
      // 过滤掉不可配送的商品
      if (!cItems[j].isDelivery || (comboItemDto && !comboItemDto.isDelivery)) continue
      basketReqData.push({
        basketId: cItems[j].basketId, isChecked: !checked ? 1 : 0
      })
    }
  })
  onShopCartSelect()
}

/**
 * 全选
 */
const onCheckAll = () => {
  let allCheckedState = allChecked.value
  allCheckedState = !allCheckedState // 改变状态
  const isShopCarts = shopCarts.value
  isShopCarts.forEach(shopCart => {
    shopCart.checked = allCheckedState
    const shopCartItemDiscounts = shopCart.shopCartItemDiscounts
    for (let i = 0; i < shopCartItemDiscounts.length; i++) {
      const cItems = shopCartItemDiscounts[i].shopCartItems
      const comboItemDto = shopCartItemDiscounts[i].chooseComboItemDto
      for (let j = 0; j < cItems.length; j++) {
        // 过滤掉不可配送的商品
        if (!cItems[j].isDelivery || (comboItemDto && !comboItemDto.isDelivery)) continue
        cItems[j].checked = allCheckedState
        basketReqData.push({ basketId: cItems[j].basketId, isChecked: allCheckedState ? 1 : 0 })
      }
    }
  })
  onShopCartSelect()
}

/**
 * 购物车 勾选/取选 事件
 */
const onShopCartSelect = () => {
  http.post('/p/shopCart/checkItems', basketReqData).then(() => {
    loadBasketData()
  })
}

/**
 * 检查全选状态
 */
const checkAllSelected = () => {
  let allCheckedState = true
  const isShopCarts = shopCarts.value
  let flag = false
  isShopCarts.forEach(shopCart => {
    let shopChecked = true
    const shopCartItemDiscounts = shopCart.shopCartItemDiscounts
    for (let i = 0; i < shopCartItemDiscounts.length; i++) {
      const cItems = shopCartItemDiscounts[i].shopCartItems
      const comboItemDto = shopCartItemDiscounts[i].chooseComboItemDto
      for (let j = 0; j < cItems.length; j++) {
        // 如果有一个商品（不是套餐且可配送或者是套餐且套餐所有商品可配送）未勾选，则店铺和全选未勾选
        if (!cItems[j].isChecked && ((!comboItemDto && cItems[j].isDelivery) || (comboItemDto && comboItemDto.isDelivery))) {
          shopChecked = false
          allCheckedState = false
          flag = true
        }
        // 购物车只有不可配送商品时
        if (isShopCarts.length === 1 && shopCartItemDiscounts.length === 1 && cItems.length === 1 && cItems[j].isDelivery === false) {
          shopChecked = false
          allCheckedState = false
          flag = true
        }
      }
      if (flag) {
        flag = false
        break
      }
    }
    shopCart.checked = shopChecked
  })
  allChecked.value = allCheckedState
  shopCarts.value = isShopCarts
}

/**
 * 修改购物车数量
 */
const onChangeNumber = (shopIndex, shopCartItemIndex, prodIndex, count, input = false) => {
  const prod = shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].shopCartItems[prodIndex]
  const matchingSkuIds = []
  if ((((prod.prodCount === 1 && count === -1) || (prod.prodCount === 9999 && count === 1)) && !prod.comboId) ||
      (prod.comboId && ((count === -1 && shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].chooseComboItemDto.comboCount === 1) || (count === 1 && shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].chooseComboItemDto.comboCount === 9999)))) {
    return
  }
  if (prod.comboId) {
    shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].shopCartItems.forEach(el => {
      if (el.parentBasketId === prod.basketId) {
        matchingSkuIds.push(el.skuId)
      }
    })
    // 不是输入框输入
    if (!input) {
      shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].chooseComboItemDto.comboCount += count
    }
  } else {
    // 不是输入框输入
    if (!input) {
      prod.prodCount += count
    }
    shopCarts.value[shopIndex].shopCartItemDiscounts[shopCartItemIndex].shopCartItems[prodIndex] = prod
  }
  totalChangeNum += count
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    timer = null
    updateBasket(prod, totalChangeNum, null, matchingSkuIds)
    totalChangeNum = 0
  }, 350)
}

/**
 * 设置sku
 */
const onSetSku = (sku) => {
  const isCurrentProdItem = currentProdItem
  const matchingSkuIds = []
  if (isCurrentProdItem.comboId) {
    isCurrentProdItem.comboList.forEach(el => {
      if (el.basketId != isCurrentProdItem.basketId) {
        matchingSkuIds.push(el.skuId)
      }
    })
  }
  updateBasket(isCurrentProdItem, isCurrentProdItem.prodCount, sku, matchingSkuIds)
}

/**
 * 修改 购物车数量、sku、满减活动
 * @param {Object} prod 修改的商品项
 * @param {Number} count 商品数量增量
 * @param {Object} sku 修改的sku
 * @param matchingSkuIds
 */
const updateBasket = (prod, count, sku = null, matchingSkuIds) => {
  currentProdItem = prod
  const updateBasketParam = {
    basketId: prod.basketId,
    comboId: prod.comboId || undefined,
    discountId: switchDiscountId || prod.discountId,
    count: sku ? prod.prodCount : count,
    oldSkuId: sku ? prod.skuId : undefined,
    matchingSkuIds: prod.comboId ? matchingSkuIds : undefined,
    prodId: prod.prodId,
    shopId: prod.shopId,
    skuId: sku ? sku.skuId : prod.skuId
  }
  http.post('/p/shopCart/changeItem', updateBasketParam).then(() => {
    if (updateBasketParam.count && updateBasketParam.count >= 1 && !updateBasketParam.discountId && !updateBasketParam.oldSkuId) {
      const flowAnalysisLogDto = JSON.parse(localStorage.getItem('bbcFlowAnalysisLogDto')) || {}
      flowAnalysisLogDto.bizData = updateBasketParam.prodId
      flowAnalysisLogDto.bizType = 0
      localStorage.setItem('bbcFlowAnalysisLogDto', JSON.stringify(flowAnalysisLogDto))
      tapLog(4, updateBasketParam.count)
    }
    loadBasketData()
    showDiscountsList.value = false
    switchDiscountId = ''
  })
}
// 检查要删除的商品个数
const checkDeleteProdNum = () => {
  if (delBasketIds.length !== 1) {
    const isShopCarts = shopCarts.value
    isShopCarts.forEach(shopCart => {
      const shopCartItemDiscounts = shopCart.shopCartItemDiscounts
      for (let i = 0; i < shopCartItemDiscounts.length; i++) {
        const cItems = shopCartItemDiscounts[i].shopCartItems
        for (let j = 0; j < cItems.length; j++) {
          if (cItems[j].checked) {
            delBasketIds.push(cItems[j].basketId)
          }
        }
      }
    })
  }
  if (delBasketIds.length === 0) {
    ElMessage({
      message: $t('cart.pleaseSelectAtLeastOneItem'),
      type: 'warning',
      duration: 1000
    })
    return
  }
  isPopup.value = true
}

/**
 * 删除购物车商品
 */
const onDeleteProd = () => {
  http.put('/p/shopCart/deleteItem', delBasketIds).then(() => {
    loadBasketData()
    getExpiryProdList() // 获取过期的商品列表
    isPopup.value = false
  })
}

/**
 * 当前选中的活动id
 */
const radioChange = (discountId) => {
  switchDiscountId = discountId
}

/**
 * 修改促销活动
 */
const onChooseDiscount = (prod) => {
  currentProdItem = prod
  if (prod.discountId !== switchDiscountId) {
    updateBasket(prod, 0)
  } else {
    showDiscountsList.value = false
  }
}

/**
 * 促销按钮
 */
const onShowDisList = (val, discountId) => {
  showDiscountsList.value = true
  currentBasketId.value = val
  switchDiscountId = discountId || -1
}

/**
 * 价格处理
 */
const parsePrice = (value) => {
  let val = Number(value)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

/**
 * 获取购物车商品总数
 */
const cartNumberStore = useCartNumberStore()

const getCartCount = () => {
  http.get('/p/shopCart/prodCount').then(({ data }) => {
    cartNumberStore.changeCartNumber(data)
  })
}

/**
 * 根据商品id获取skuList
 * @param {Object} prod 当前要修改的选项
 */
const getSkuListByProdId = (prod) => {
  const comboList = []
  if (prod.comboId) {
    const isShopCarts = shopCarts.value
    const shopIndex = isShopCarts.findIndex(el => el.shopId === prod.shopId)
    const shopCartItemDiscounts = isShopCarts[shopIndex].shopCartItemDiscounts
    const shopCartItemIndex = shopCartItemDiscounts.findIndex(el => el.chooseComboItemDto.comboId === prod.comboId)
    shopCartItemDiscounts[shopCartItemIndex].shopCartItems.forEach(el => {
      comboList.push({
        basketId: el.basketId,
        skuId: el.skuId,
        prodId: el.prodId
      })
    })
    prod.comboList = comboList
  }
  currentProdItem = prod
}

const expiryProdList = ref([]) // 失效商品列表

/**
 * 失效商品列表
 */
const getExpiryProdList = () => {
  const params = {
    url: '/p/shopCart/expiryProdList',
    method: 'GET'
  }
  http(params).then(({ data: res }) => {
    const prodList = []
    res.forEach(item => {
      item.shopCartItemDtoList.forEach(prod => {
        prod.checked = false
        prodList.push(prod)
      })
    })
    expiryProdList.value = prodList
  })
}

</script>
<style lang="scss" scoped>
@use './index.scss';
</style>
